const { createApp, ref, reactive, computed, onMounted, watch } = Vue;
const { ElMessage, ElMessageBox, ElNotification } = ElementPlus;

// API基础URL配置
const API_BASE_URL = 'http://localhost:8080';

// API封装
const api = {
    // 统计概览
    getStatisticsOverview: () => axios.get(`${API_BASE_URL}/api/statistics/overview`),
    
    // 门店列表
    getShops: () => axios.get(`${API_BASE_URL}/api/shop/list`),
    getShopDetail: (shopId) => axios.get(`${API_BASE_URL}/api/shop/${shopId}`),
    
    // 传感器列表
    getSensors: () => axios.get(`${API_BASE_URL}/api/sensor/list`),
    getSensorDetail: (sensorId) => axios.get(`${API_BASE_URL}/api/sensor/${sensorId}`),
    getSensorRealtimeData: (sensorId) => axios.get(`${API_BASE_URL}/api/sensor/${sensorId}/realtime`),
    
    // 传感器配置
    updateSensorConfig: (sensorId, config) => axios.put(`${API_BASE_URL}/api/sensor/${sensorId}/config`, config),
    setCurrentAsBaseline: (sensorId) => axios.post(`${API_BASE_URL}/api/sensor/${sensorId}/set-baseline`),
    
    // 网关列表
    getGateways: () => axios.get(`${API_BASE_URL}/api/gateway/list`),
    
    // 电力设备
    getPowerDevices: () => axios.get(`${API_BASE_URL}/api/power-device/list`),
    getPowerDeviceStatus: (merchantId) => axios.get(`${API_BASE_URL}/api/power-device/status/${merchantId}`),
    
    // 告警列表
    getAlarms: (params) => axios.get(`${API_BASE_URL}/api/alarm/list`, { params }),
    getUnconfirmedAlarms: () => axios.get(`${API_BASE_URL}/api/alarm/unconfirmed`),
    confirmAlarm: (alarmId, handler) => axios.post(`${API_BASE_URL}/api/alarm/${alarmId}/confirm`, { handler }),
    
    // 巡检记录
    getInspectionHistory: (shopId) => axios.get(`${API_BASE_URL}/api/statistics/inspection-history/${shopId}`),
    
    // 传感器数据
    getSensorDataHistory: (sensorId, params) => axios.get(`${API_BASE_URL}/api/statistics/sensor-data/${sensorId}`, { params }),
};

// 主应用组件
const AppComponent = {
    setup() {
        // 响应式状态
        const state = reactive({
            loading: true,
            activeTab: 'overview', // overview, shops, sensors, alarms, power, settings
            statistics: null,
            shops: [],
            sensors: [],
            gateways: [],
            powerDevices: [],
            alarms: [],
            selectedShop: null,
            selectedSensor: null,
            autoRefresh: true,
            refreshInterval: 5000, // 5秒
        });
        
        // 定时器
        let refreshTimer = null;
        
        // 加载统计概览
        const loadStatistics = async () => {
            try {
                const response = await api.getStatisticsOverview();
                state.statistics = response.data;
            } catch (error) {
                console.error('加载统计数据失败:', error);
                ElMessage.error('加载统计数据失败');
            }
        };
        
        // 加载门店列表
        const loadShops = async () => {
            try {
                const response = await api.getShops();
                state.shops = response.data;
            } catch (error) {
                console.error('加载门店列表失败:', error);
                ElMessage.error('加载门店列表失败');
            }
        };
        
        // 加载电力设备列表
        const loadPowerDevices = async () => {
            try {
                const response = await api.getPowerDevices();
                state.powerDevices = response.data;
            } catch (error) {
                console.error('加载电力设备列表失败:', error);
                ElMessage.error('加载电力设备列表失败');
            }
        };
        
        // 加载传感器列表
        const loadSensors = async () => {
            try {
                const response = await api.getSensors();
                state.sensors = response.data;
            } catch (error) {
                console.error('加载传感器列表失败:', error);
                ElMessage.error('加载传感器列表失败');
            }
        };
        
        // 加载网关列表
        const loadGateways = async () => {
            try {
                const response = await api.getGateways();
                state.gateways = response.data;
            } catch (error) {
                console.error('加载网关列表失败:', error);
                ElMessage.error('加载网关列表失败');
            }
        };
        
        // 加载告警列表
        const loadAlarms = async () => {
            try {
                const response = await api.getUnconfirmedAlarms();
                state.alarms = response.data;
            } catch (error) {
                console.error('加载告警列表失败:', error);
            }
        };
        
        // 刷新所有数据
        const refreshAllData = async () => {
            await Promise.all([
                loadStatistics(),
                loadShops(),
                loadSensors(),
                loadGateways(),
                loadPowerDevices(),
                loadAlarms(),
            ]);
        };
        
        // 切换标签页
        const switchTab = (tab) => {
            state.activeTab = tab;
        };
        
        // 查看门店详情
        const viewShop = (shop) => {
            state.selectedShop = shop;
        };
        
        // 查看传感器详情
        const viewSensor = async (sensor) => {
            try {
                const response = await api.getSensorDetail(sensor.sensorId);
                state.selectedSensor = response.data;
            } catch (error) {
                console.error('加载传感器详情失败:', error);
                ElMessage.error('加载传感器详情失败');
            }
        };
        
        // 获取门店的传感器
        const getShopSensors = (shopId) => {
            return state.sensors.filter(s => s.shopId === shopId);
        };
        
        // 切换自动刷新
        const toggleAutoRefresh = () => {
            state.autoRefresh = !state.autoRefresh;
        };
        
        // 刷新数据
        const refreshData = () => {
            refreshAllData();
        };
        
        // 确认告警
        const confirmAlarm = async (alarm) => {
            try {
                await ElMessageBox.prompt('请输入处理人姓名', '确认告警', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    inputPattern: /.+/,
                    inputErrorMessage: '请输入处理人姓名'
                });
                
                await api.confirmAlarm(alarm.id, prompt.value);
                ElMessage.success('告警已确认');
                await loadAlarms();
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('确认告警失败:', error);
                    ElMessage.error('确认告警失败');
                }
            }
        };
        
        // 获取状态标签
        const getStateTag = (state) => {
            if (state === 'closed') return { text: '已关闭', type: 'success' };
            if (state === 'open') return { text: '已开启', type: 'danger' };
            return { text: '未知', type: 'info' };
        };
        
        // 获取在线状态标签
        const getOnlineTag = (isOnline) => {
            return isOnline 
                ? { text: '在线', type: 'success' }
                : { text: '离线', type: 'danger' };
        };
        
        // 格式化时间
        const formatTime = (time) => {
            if (!time) return '-';
            return new Date(time).toLocaleString('zh-CN');
        };
        
        // 启动自动刷新
        const startAutoRefresh = () => {
            if (refreshTimer) clearInterval(refreshTimer);
            if (state.autoRefresh) {
                refreshTimer = setInterval(() => {
                    refreshAllData();
                }, state.refreshInterval);
            }
        };
        
        // 停止自动刷新
        const stopAutoRefresh = () => {
            if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;
            }
        };
        
        // 监听自动刷新开关
        watch(() => state.autoRefresh, (newVal) => {
            if (newVal) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });
        
        // 组件挂载时
        onMounted(async () => {
            state.loading = true;
            await refreshAllData();
            state.loading = false;
            startAutoRefresh();
        });
        
        // 返回
        return {
            state,
            switchTab,
            viewShop,
            viewSensor,
            getShopSensors,
            toggleAutoRefresh,
            refreshData,
            confirmAlarm,
            loadPowerDevices,
            getStateTag,
            getOnlineTag,
            formatTime,
            refreshAllData,
        };
    },
    
    template: `
        <div v-if="state.loading" class="loading-container">
            <div class="loading-text">
                🔒 店铺三关一闭监控系统加载中...
            </div>
        </div>
        
        <div v-else id="main-app">
            <!-- 顶部导航栏 -->
            <header-nav 
                :active-tab="state.activeTab"
                :statistics="state.statistics"
                :auto-refresh="state.autoRefresh"
                @switch-tab="switchTab"
                @toggle-refresh="state.autoRefresh = !state.autoRefresh"
                @refresh="refreshAllData"
            />
            
            <!-- 主内容区 -->
            <main class="main-content">
                <!-- 概览页 -->
                <overview-page 
                    v-if="state.activeTab === 'overview'"
                    :statistics="state.statistics"
                    :shops="state.shops"
                    :sensors="state.sensors"
                    :alarms="state.alarms"
                    @view-shop="viewShop"
                    @view-sensor="viewSensor"
                />
                
                <!-- 门店列表页 -->
                <shops-page 
                    v-if="state.activeTab === 'shops'"
                    :shops="state.shops"
                    :sensors="state.sensors"
                    @view-shop="viewShop"
                />
                
                <!-- 传感器列表页 -->
                <sensors-page 
                    v-if="state.activeTab === 'sensors'"
                    :sensors="state.sensors"
                    @view-sensor="viewSensor"
                />
                
                <!-- 电力设备页 -->
                <power-devices-page 
                    v-if="state.activeTab === 'power'"
                    :power-devices="state.powerDevices"
                    @refresh="loadPowerDevices"
                />
                
                <!-- 告警列表页 -->
                <alarms-page 
                    v-if="state.activeTab === 'alarms'"
                    :alarms="state.alarms"
                    @confirm-alarm="confirmAlarm"
                />
                
                <!-- 传感器详情页 -->
                <sensor-detail-page 
                    v-if="state.activeTab === 'sensor-detail' && state.selectedSensor"
                    :sensor="state.selectedSensor"
                    @back="switchTab('sensors')"
                />
            </main>
        </div>
    `
};

// 导出到全局
window.app = AppComponent;

